<template>
	<view>
		<!-- 首先我们需要在页面上创建一个canvas，然后因为canvas 是系统组件它的层级最高，所以会导致一直显示在页面上，如果你需要查看效果图，那么可以暂时不理，最后实现的时候我们需要给他一个样式`position: absolute; top: -10000rpx;`。让它定位到页面可视区域之外，不能让用户查看到它。 -->
		<canvas canvas-id="mycanvas" class="canvas-style" style="" />
		<uni-popup ref="popup" type="center" background-color="#fff" @touchmove.stop.prevent="">
			<view class="shareImagePath">
				<image :src="shareImagePath" mode="widthFix"></image>
				<!-- <image src="../../static/logo.png" mode="widthFix"></image> -->
				<button @click="savePhoto">保存名片</button>
				<view @click="closePoster">
					<uni-icons type="close" color="#fff" size="40"></uni-icons>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		queryShareQRCode
	} from "@/request/api.js";
	import util from "@/utils/util.js";
	export default {
		name: "posterGeneration",
		data() {
			return {
				shareImagePath: "",
				// qtsheBackground: require("../../static/inviteFriends.jpg"),
				qrcode: require("../../static/logo.png"),
				time: '',
			};
		},
		mounted() {

			// this.getQrcode();
		},
		methods: {
			// 关闭海报弹窗
			closePoster() {
				this.$refs.popup.close();
				// this.shareImagePath='';
			},

			savePhoto() {
				var that = this

				wx.showLoading({
					title: '正在保存...',
					mask: true
				})
				// setTimeout(() => {
				uni.downloadFile({
					url: that.shareImagePath, //仅为示例，并非真实的资源
					success: (res) => {
						if (res.statusCode === 200) {
							console.log('下载成功');
							uni.saveImageToPhotosAlbum({
								filePath: res.tempFilePath,
								success(res) {
									uni.showToast({
										title: '保存成功',
										icon: 'none'
									})
									setTimeout(() => {
										uni.hideLoading()
										that.$refs.popup.close();
									}, 300)
								},
								fail() {
									uni.showToast({
										title: '保存失败，请刷新页面重试',
										icon: 'none'
									})
									setTimeout(() => {
										uni.hideLoading()
										that.$refs.popup.close();
									}, 300)
								}
							})
						}
					}
				});

				// }, 2500)
			},
			//将文字绘制到canvas的固定位置
			setText(context, text, len, align, left, height, size, row = 5, color) {
				context.setFontSize(size)
				context.fillStyle = color;
				context.textAlign = align;
				if (text.length == len || len < 25) {
					text = text.substring(0, len - 1) + '...'
					context.fillText(text, left, height)
				} else if (len > 25) {
					var textArray = [];
					let temp = '';
					let w = 350;
					for (let i = 0; i < text.length; i++) {
						if (context.measureText(temp).width < w && context.measureText(temp + (text[i])).width <= w) {
							temp += text[i];
						} else {
							textArray.push(temp);
							temp = text[i];
						}
					}
					textArray.push(temp)
					for (let b = 0; b < textArray.length; b++) {
						if (b < row) {
							context.fillText(textArray[b], left, height + (b + 1) * 20); //每行字体y坐标间隔20
						} else if (b == row) {
							this.setText(context, textArray[b], textArray[b].length, align, left, height + (b + 1) * 20,
								size);
						}
					}
				} else {
					context.fillText(text, left, height)
				}

			},
			getMiao(text) {
				let newTime = new Date().getTime();
				console.log(text + `${(newTime-this.time)/1000}秒`);

				this.time = newTime;
			},
			async getQrcode() {
				let that = this;
				this.time = new Date().getTime();
				this.$refs.popup.open("center");
				let res = await queryShareQRCode({
					method: "GET",
					data: {

					},
				});
				uni.showToast({
					title: res.code == 200 ? "海报生成成功!" : res.message,
					icon: res.code == 200 ? 'success' : 'none',
					duration:500
				})
				this.shareImagePath = res.result.qrcodeUrl;
				return;
				this.getMiao('获取二维码接口调用时间:');

				uni.showLoading({
					title: "海报生成中..."
				})
				let context = uni.createCanvasContext('mycanvas', this);
				let img = await util.downloadFileFn(res.result.backgroupdImageUrl);
				this.getMiao('下载海报图片:');
				let qrcode = await util.downloadFileFn(res.result.qrcodeUrl);
				this.getMiao('下载二维码:');
				context.beginPath()
				context.setFillStyle("#ffffff"); // 设置背景白色
				context.fillRect(0, 0, 375, 667)
				context.drawImage(img, 0, 0, 375, 480);
				context.drawImage(qrcode, 50, 515, 80, 80);
				that.setText(context, res.result.userId, 5000, 'left', 150, 520, 18, 1, "#000");
				that.setText(context, "邀请您加入优选团餐", 5000, 'left', 150, 560, 18, 1, "#000");
				that.setText(context, "--- 长按识别或扫描二维码进入 ---", 500000, 'center', 187.5, 615, 18, 1, "#ccc");
				//绘制图片
				context.draw()
				context.save()
				//将生成好的图片保存到本地，需要延迟一会，绘制期间耗时
				setTimeout(() => {
					uni.canvasToTempFilePath({
						canvasId: 'mycanvas',
						width: 375,
						height: 667,
						// destWidth:485,
						// destHeight:900,
						quality: 1,
						success: function(res) {
							that.getMiao('绘制海报:');
							uni.hideLoading()
							uni.showToast({
								title: "海报生成成功!"
							})
							that.shareImagePath = res.tempFilePath;
						},
						fail: function(res) {
							console.log(res.errMsg)
						}
					}, this)
				}, 2000)
			},
		}
	}
</script>

<style lang="scss" scoped>
	/* 画布样式 */
	.canvas-style {
		width: 750rpx !important;
		height: 1334rpx !important;
		margin: 0 auto;
		position: fixed;
		top: -10000rpx;
		left: 50%;
		transform: translate(-50%, -0%);
		/* display: none; */
	}

	.shareImagePath {
		position: fixed !important;
		width: 750rpx !important;
		background: transparent !important;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		/* display: none; */
	}

	.shareImagePath image {
		display: block;
		// width:562.5rpx!important;
		// height:1000.5rpx!important;
		width: 562.5rpx !important;
		height: 900.5rpx !important;
		margin: 0 auto;
		// background: #fff;
	}

	.shareImagePath button {
		background: #EB5B1E;
		color: #fff;
		margin: 30rpx auto 0;
		width: 60%;
		height: 80rpx;
		line-height: 80rpx;
		border-radius: 60rpx;
	}

	.shareImagePath>view {
		display: flex;
		justify-content: center;
		align-items: center;
		width: 40rpx;
		height: 40rpx;
		margin: 30rpx auto 0;
		border-radius: 50%;
	}
</style>